"""
拼装对应 mqtt 消息接口
"""

from typing import Dict
import time


def __set_time(message: Dict) -> Dict:
    """
    给消息添加时间戳
    """
    # 新版本
    message["time"] = int(time.time())

    # 旧版本
    # message["data"]["time"] = int(time.time())

    return message


def set_tap_zoom_point(multiplier, focus_x, focus_y) -> Dict:
    message = {
        "type": "setTapZoomPoint",
        "data": {"x": focus_x, "y": focus_y, "multiplier": multiplier},
    }
    return __set_time(message)


def set_tap_point(focus_x, focus_y) -> Dict:
    message = {
        "type": "setTapPoint",
        "data": {
            "x": focus_x,
            "y": focus_y,
        },
    }
    return __set_time(message)


def set_wide_camera() -> Dict:
    message = {
        "type": "setCameraSource",
        "data": {
            "source": "wide",
        },
    }
    return __set_time(message)


def set_zoom_camera() -> Dict:
    message = {
        "type": "setCameraSource",
        "data": {
            "source": "zoom",
        },
    }
    return __set_time(message)


def set_camera_zoom(focus) -> Dict:
    message = {
        "type": "setCameraZoom",
        "data": {"focus": focus},
    }
    return __set_time(message)


import paho.mqtt.client as mqtt
import json


import os, sys, traceback

parent_path = os.path.abspath(os.path.join(__file__, *([".."] * 3)))
sys.path.insert(0, parent_path)

from core.utils.logger import logging


class Mqtt(object):
    def __init__(self, ip: str, port: int, user: str, passwd: str, send_topic: str):
        self.__ip = ip
        self.__port = port
        self.__user = user
        self.__passwd = passwd
        self.__send_topic = send_topic
        self.__client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

    def start(self):
        self.__client.username_pw_set(self.__user, self.__passwd)
        self.__client.connect(self.__ip, self.__port, 10)
        # 启动网络循环
        self.__client.loop_start()

    def close(self):
        self.__client.loop_stop()
        self.__client.disconnect()

    def __call__(self, message: Dict):
        message = json.dumps(message)
        logging.info(f"输出 mqtt 消息 : {message}")
        self.__client.publish(self.__send_topic, payload=message, qos=0, retain=False)


if __name__ == "__main__":
    # multiplier 逻辑为变焦倍率为几倍
    message = set_tap_zoom_point(2, 0.5, 0.3)
    print(message)

    # x,y  0.5,0.3 向上 0.5,0.8 向下
    message = set_tap_point(0.5, 0.5)
    print(message)

    message = set_wide_camera()
    print(message)

    message = set_zoom_camera()
    print(message)

    message = set_camera_zoom(2)
    print(message)

    mqtt = Mqtt(
        ip="36.139.11.140",
        port=1883,
        user="admin",
        passwd="Gdet@mqtt2024.",
        send_topic="/TEST_M30T_001/uavfc/command",
    )
    mqtt.start()
    mqtt(message)

    # while True:
    #     time.sleep(1)

    time.sleep(1)
    mqtt.close()
